package org.ping.websocket;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import org.jsping.entity.Message;
import org.jsping.util.RedisUtil;
import org.jsping.util.SerializationUtil;

import redis.clients.jedis.Jedis;

public class MessageQueue {
	
	private MessageQueue() {}
	
	private static MessageQueue msg = null;
	
	public static MessageQueue getInstance() {
		if(msg == null) {
			synchronized (MessageQueue.class) {
				if(msg==null) {
					msg = new MessageQueue();
				}
			}
		}
		return msg;
	}
	//存储所有的还没发送的用户消息
	public Map<Integer,LinkedList<Message>> mess = new HashMap<Integer,LinkedList<Message>>();
	
	/**
	 * 返回某个用户的所有未发送消息
	 * @param id 根据用户id获取
	 * @return 
	 */
	public LinkedList<Message> getUserMag(int id) {
//		System.out.println("1230----->");
//		Jedis j = RedisUtil.getJedis();
//		byte[] link = j.get(SerializationUtil.serialize(id));
//		System.out.println(j.ping());
//		if(link==null) {
//			return null;
//		}
//		LinkedList<Message> mess =(LinkedList<Message>) SerializationUtil.deserialize(link);
//		System.out.println("1230----->");
//		return mess;
		
		return mess.get(id)==null?null:mess.get(id);
	}
	/**
	 * 给这个用户增加一条消息
	 * @param id
	 * @param me
	 */
	public void setUserMag(int id,Message me) {
		mess.get(id).add(me);
		
//		Jedis j = RedisUtil.getJedis();
//		System.out.println(j.ping());
//		@SuppressWarnings("unchecked")
//		LinkedList<Message> list = (LinkedList<Message>) SerializationUtil.deserialize(j.get(SerializationUtil.serialize(id)));
//		list.add(me);
//		this.setUserLinkedList(id, list);
//		j.close();
	}
	/**
	 * 给用户增加一个缓存队列
	 * @param id
	 * @param list
	 */
	public void setUserLinkedList(int id,LinkedList<Message> list) {
//		Jedis j = RedisUtil.getJedis();
//		j.set(SerializationUtil.serialize(id), SerializationUtil.serialize(list));
//
//		System.out.println(j.ping()+"--->");
//		j.close();
		
		mess.put(id, list);
	}
	
	public void del(int id) {
		Jedis j = RedisUtil.getJedis();
		System.out.println(j.ping());
		j.del(SerializationUtil.serialize(id));
		System.out.println(id+"用户缓存消息删除成功！");
		j.close();
	}
	
}
